package edu.sctu.lab03;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;


public class LoginServerlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        resp.setCharacterEncoding("utf8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        DataBase dataBase = new DataBase();

        List<User> userList = dataBase.getUserList();

        int a = 0;
        for (User user : userList) {
            if (user.getName().equals(username) && user.getPassword().equals(password)) {
                a = 1;
                HttpSession session = req.getSession();
                session.setAttribute("isLogin", "true");
                session.setAttribute("user", user);
            }
        }
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        if ( a == 1){
            resp.sendRedirect("http://localhost:8080/userList");

        }else if(a == 0){
            PrintWriter out = resp.getWriter();
            out.write("用户名或密码错误！");

        }
    }

}
